package com.xzy.sms.web.domain.controller;

import java.io.IOException;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.xzy.sms.core.service.SendSmsServiceImpl;
import com.xzy.sms.entity.SendSmsRequest;
import com.xzy.sms.web.domain.entity.Application;
import com.xzy.sms.web.domain.entity.Template;
import com.xzy.sms.web.domain.service.ApplicationService;
import com.xzy.sms.web.domain.service.TemplateService;
import com.xzy.sms.web.rest.RestObject;
import com.xzy.sms.web.system.utils.UserUtils;

/**
 * @desc 
 * @author wjw
 * @time 2017年11月16日下午4:25:47
 */
@Controller
@RequestMapping("/sms")
public class SmsController {
    
    /** 日志打印器 */
    protected static Logger logger = LoggerFactory.getLogger(SmsController.class);
    
    /** FIXME */
    @Autowired
    private SendSmsServiceImpl sendSmsServiceImpl;
    
    /** FIXME */
    @Autowired
    private ApplicationService spplicationService;
    
    /** FIXME */
    @Autowired
    private TemplateService templateService;
    
    /**
     * FIXME 方法注释信息(此标记由Eclipse自动生成,请填写注释信息删除此标记)
     * 
     * @param appId 应用Id
     * @param sms x
     * @return x
     */
    @RequestMapping(value = "/sendtest")
    public String sendSmsTest() {
        return "sms/smstest";
    }
    
    /**
     * FIXME 方法注释信息(此标记由Eclipse自动生成,请填写注释信息删除此标记)
     * 
     * @param ssr xx
     * @param request xx
     * @return x
     */
    @RequestMapping(value = "/send")
    @ResponseBody
    public RestObject send(SendSmsRequest ssr, HttpServletRequest request, HttpServletResponse response) {
        // 获取当前的请求路径
        String url = request.getRequestURL().substring(0, request.getRequestURL().lastIndexOf("/sms/send"));
        url += "/api/send";
        // 发送的请求参数
        FormEncodingBuilder form = new FormEncodingBuilder();
        form.add("sign", "test");
        // 获取模板参数
        Enumeration<String> keys = request.getParameterNames();
        while (keys.hasMoreElements()) {
            String key = keys.nextElement();
            form.add(key, StringUtils.trimToEmpty(request.getParameter(key)));
        }
        
        OkHttpClient client = new OkHttpClient();
        Request req = new Request.Builder().url(url).post(form.build()).build();
        Response res;
        try {
            res = client.newCall(req).execute();
            if (res.isSuccessful()) {
                response.getWriter().print(res.body().string());
                return null;
            } else {
                return RestObject.newError("发送测试失败,不正确的返回值状态");
            }
        } catch (IOException ex) {
            logger.error("短信测试失败", ex);
            return RestObject.newError("发送测试失败");
        }
        
    }
    
    /**
     * FIXME 方法注释信息(此标记由Eclipse自动生成,请填写注释信息删除此标记)
     * 
     * @param appId 应用Id
     * @param sms x
     * @return x
     */
    @RequestMapping(value = "/application")
    @ResponseBody
    public RestObject getApplicationByUserId() {
        String userId = UserUtils.getUserId();
        List<Application> data = spplicationService.findByUserId(userId);
        
        return RestObject.newOk(data);
    }
    
    /**
     * FIXME 方法注释信息(此标记由Eclipse自动生成,请填写注释信息删除此标记)
     * 
     * @param appId 应用Id
     * @param sms x
     * @return x
     */
    @RequestMapping(value = "/template")
    @ResponseBody
    public RestObject getTemplateByUserId() {
        String userId = UserUtils.getUserId();
        List<Template> data = templateService.findByUserId(userId);
        
        return RestObject.newOk(data);
    }
    
}
